import { UpOutlined } from '@ant-design/icons';
import { Checkbox } from 'antd';
import { DatasetList } from '../select-know-modal';
import { useState } from 'react';

interface Props {
  data: DatasetList[];
  checkedValue: DatasetList[];
  level?: number;
  onChange: (e: DatasetList, data: DatasetList[]) => void;
  onRequest: (value: DatasetList) => void;
}

const CheckBoxTree = ({ data, level = 0, onChange, onRequest, checkedValue }: Props) => {
  const [expandedIds, setExpandedIds] = useState<string[]>([]);

  // 切换展开状态
  const handleToggleExpand = (itemId: string) => {
    setExpandedIds((prev) =>
      prev.includes(itemId) ? prev.filter((id) => id !== itemId) : [...prev, itemId],
    );
  };

  return data.map((item) => {
    const isExpanded = expandedIds.includes(item.id);

    return (
      <div
        key={item.id}
        className="flex flex-col gap-[15px]"
        style={{
          paddingLeft: level === 0 ? 0 : `20px`,
        }}
      >
        <div className="flex items-center justify-between">
          <Checkbox
            value={item}
            onChange={(e) => onChange(e.target.value, data)}
            checked={checkedValue?.some((v) => v.id === item.id)}
          >
            {item.name}
          </Checkbox>

          {/* {item.children && <UpOutlined className="cursor-pointer" />} */}
          {item.type === 'folder' && (
            <UpOutlined
              className="cursor-pointer"
              onClick={() => {
                handleToggleExpand(item.id);
                if (!item.children) {
                  onRequest(item);
                }
              }}
              style={{
                transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                transition: 'transform 0.3s',
              }}
            />
          )}
        </div>

        {isExpanded && item.children && (
          <CheckBoxTree
            data={item.children}
            level={level + 1}
            onChange={onChange}
            onRequest={onRequest}
            checkedValue={checkedValue}
          />
        )}
      </div>
    );
  });
};

export default CheckBoxTree;
